<?php
namespace jy_weishop\activity;
defined('BY_JYA') or exit('error');
/*
	促销
*/
class sales extends \plugin{
	public function goods_list($psize=10,$page=1,$total=null){
		$params=array(
			'uniacid'=>$_SESSION['uniacid'],
			'end_time >'=>TIMESTAMP,
		);
		$pindex = max(1, intval($page));
		$parameter=array(
			'params'=>$params,
			'limit'=>array($pindex,$psize),
			'fields'=>array('goods_id'),
		);
		$list=$this->get_list('activity_sales',$parameter,$total);
		if($list){
			foreach($list as &$item){
				$goods=$this->model('goods')->goods_detail($item['goods_id'],array('id','title','image','price','marketprice','total'));
				$item=array_merge($item,$goods);
			}
		}
		return $list;
	}
	public function get_active($goods_id,$active_id){
		$active=$this->get('activity_sales',array('id'=>$active_id));
		if(!$active){
			return false;
		}
		if($active['stop'] ||  $active['end_time']<TIMESTAMP){
			return false;
		}
		if($active['start_time']<TIMESTAMP && $active['end_time']>TIMESTAMP){
			$status=1;
			$rest_time=$this->model()->date($active['end_time']-TIMESTAMP);
			$rest_time2=$active['end_time'];
		}
		if($active['start_time']>TIMESTAMP){
			$status=0;
			$rest_time=$this->model()->date($active['start_time']-TIMESTAMP);
			$rest_time2=$active['start_time'];
		}
		$active_price=price($active['price'],true);
		$count=pdo_getsum('jy_weishop_activity_sales_log',array('uniacid'=>$_SESSION['uniacid'],'active_id'=>$active_id),'num');
		$percent = ceil(($count / ($active['total'] ?: 1)) * 100);
		return array(
			'title'=>'促销',
			'price'=>$active_price,
			'status'=>$status,
			'end_time'=>date('Y-m-d H:i:s',$active['end_time']),
			'start_time'=>date('Y-m-d H:i:s',$active['start_time']),
			'rest_time'=>$rest_time,
			'rest_time2'=>$rest_time2,
			'percent'=>$percent
		);
	}
	public function check_stock($goods_id,$active_id,$num){
		$active=$this->get('activity_sales',array('id'=>$active_id));
		if(!$active){
			return false;
		}
		if($active['stop'] ||  $active['end_time']<TIMESTAMP){
			return false;
		}
		if($active['start_time']>TIMESTAMP){
			exi('活动还没开始！','error');
		}
		$count=pdo_getsum('jy_weishop_activity_sales_log',array('uniacid'=>$_SESSION['uniacid'],'active_id'=>$active_id),'num');
		if($active['total']<=$count){
			exi('本次活动商品已卖完！','error');
		}
		$hsnum=pdo_getsum('jy_weishop_activity_sales_log',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$_SESSION['uid'],'active_id'=>$active_id),'num');
		if($active['num']<$num+$hsnum){
			exi('该活动每人只能购买'.$active['num'].'件商品！','error');
		}
		return true;
	}
	public function buy($goods_id,$active_id,$num){
		$this->check_stock($goods_id,$active_id,$num);
		return true;
	}
	//$goods_id,$active_id,$num,$ordersn
	public function order_create($params){
		$log=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$params['mid']?:$_SESSION['uid'],
			'goods_id'=>$params['goods_id'],
			'active_id'=>$params['active_id'],
			'ordersn'=>$params['ordersn'],
			'num'=>$params['num'],
			'price'=>$params['goods_price'],
			'createtime'=>TIMESTAMP,
		);
		$this->insert('activity_sales_log',$log);
		return true;
	}
	public function getoffer(){
		$sale_offer=$this->plugin_setting('sale_offer');
		if($sale_offer['isopen']!=1){
			return false;
		}
		$weekid=date("w");
		$res['list']=$sale_offer['goods_ids'.$weekid];
		if(empty($res['list']) || count($res['list'])==0){
			return false;
		}
		$sale_offer['discount']=($sale_offer['discount']>10 && $sale_offer['discount']<=100)?$sale_offer['discount']:98;
		foreach($res['list'] as $k=>&$v){
			$options = pdo_getall('jy_weishop_goods_option',array('goodsid'=>$v['id']));
			if(!empty($options)){
				foreach($options as &$op){
					$canbuy=$this->model('goods')->check_buy($v['id'],1,$op['id'],'','',true);
					if($canbuy){
						$v['canbuy']=true;
						$v['optionsid']=$op['id'];
						$v['oldprice']=pdo_getcolumn('jy_weishop_goods_option',array('id'=>$op['id'],'uniacid'=>$_SESSION['uniacid']),'price');
						$v['price']=price($v['oldprice']*$sale_offer['discount']/100,true);
					}
				}
				if(!$v['canbuy']){
					$v['optionsid']=$options[0]['id'];
					$v['oldprice']=pdo_getcolumn('jy_weishop_goods_option',array('id'=>$options[0]['id'],'uniacid'=>$_SESSION['uniacid']),'price');
					$v['price']=price($v['oldprice']*$sale_offer['discount']/100,true);
				}
			}else{
				$v['oldprice']=pdo_getcolumn('jy_weishop_goods',array('id'=>$v['id'],'uniacid'=>$_SESSION['uniacid']),'price');
				$v['canbuy']=$this->model('goods')->check_buy($v['id'],1,'','','',true);
				$v['price']=price($v['oldprice']*$sale_offer['discount']/100,true);
			}
			$v['image']=$v['image']?tomedia($v['image']):'';
		}
		$res['title']=$sale_offer['title'];
		$res['desc']=$sale_offer['desc'];
		$res['discount']=$sale_offer['discount'];
		$weekarray=array("日","一","二","三","四","五","六"); //先定义一个数组
		$res['weekstitle']='星期'.$weekarray[$weekid];
		return $res;
	}
	public function getluck($isget=false){
		$sale_luck=$this->plugin_setting('sale_luck');
		$lucklist=array(
			array('title'=>'运气平平','ratio'=>10,'discount'=>100),
			array('title'=>'小有运气','ratio'=>25,'discount'=>98),
			array('title'=>'时来运转','ratio'=>35,'discount'=>95),
			array('title'=>'吉星高照','ratio'=>20,'discount'=>93),
			array('title'=>'鸿运当头','ratio'=>10,'discount'=>90),
		);
		$sale_luck['lucklist']=$sale_luck['lucklist']?:$lucklist;
		$daytime = mktime(0,0,0,date('m'),date('d'),date('Y'));	
		$isluck=pdo_count('jy_weishop_member_lucklog',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$_SESSION['uid'],'createtime >'=>$daytime));
		if($isget && $isluck){
			$luckkey=pdo_getcolumn('core_members',array('id'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid']),'luckkey');
		}else{
			if($isluck && !$isget){
				return false;
			}
			foreach ($sale_luck['lucklist'] as $key => $val){
			  $arr[$key] = $val['ratio']; 
			}
			//概率数组的总概率精度 
			$proSum = array_sum($arr); 
			//概率数组循环 
			foreach ($arr as $key => $v) { 
				$randNum = mt_rand(1, $proSum); 
				if ($randNum <= $v) {
				  $luckkey = $key; 
				  break; 
				} else { 
				  $proSum -= $v; 
				}    
			}
			pdo_update('core_members',array('luckkey'=>$luckkey),array('id'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid']));
			pdo_insert('jy_weishop_member_lucklog',array('luckkey'=>$luckkey,'mid'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid'],'createtime'=>TIMESTAMP));
		}
		$res=$sale_luck['lucklist'][$luckkey];
		$nickname=pdo_getcolumn('core_members',array('id'=>$_SESSION['uid']),'nickname');
		$res['settitle']=str_replace('[nickname]',$nickname,$sale_luck['title']);
		$res['setdesc']=str_replace('[nickname]',$nickname,$sale_luck['desc']);
		$res['youhuidesc']=str_replace('[nickname]',$nickname,$sale_luck['youhuidesc']);
		$res['youhuidesc']=str_replace('[lucktitle]',$res['title'],$res['youhuidesc']);
		$res['youhuidesc']=str_replace('[discount]',$res['discount'],$res['youhuidesc']);
		$res['content']=$sale_luck['content'];
		$res['setbg']=$sale_luck['bg'];
		$res['luckkey']=$luckkey;
		return $res;
	}
	public function jieluck($luckkey){
		$sale_luck=$this->plugin_setting('sale_luck');
		$lucklist=array(
			array('title'=>'运气平平','ratio'=>10,'discount'=>100),
			array('title'=>'小有运气','ratio'=>25,'discount'=>98),
			array('title'=>'时来运转','ratio'=>35,'discount'=>95),
			array('title'=>'吉星高照','ratio'=>20,'discount'=>93),
			array('title'=>'鸿运当头','ratio'=>10,'discount'=>90),
		);
		$sale_luck['lucklist']=$sale_luck['lucklist']?:$lucklist;
		$daytime = mktime(0,0,0,date('m'),date('d'),date('Y'));
		$isluck=pdo_count('jy_weishop_member_lucklog',array('uniacid'=>$_SESSION['uniacid'],'isjie'=>0,'mid'=>$_SESSION['uid'],'createtime >'=>$daytime));
		$nickname=pdo_getcolumn('core_members',array('id'=>$_SESSION['uid']),'nickname');
		$myluckkey=pdo_getcolumn('core_members',array('id'=>$_SESSION['uid']),'luckkey');
		if($myluckkey>=$luckkey){
			//不用借
			$res=$sale_luck['lucklist'][$myluckkey];
			$res['isjie']=2;
			$res['luckkey']=$myluckkey;
			$res['setdesc']=$nickname.'您运势比较好哦！无需借势！';
		}else{
			$res=$sale_luck['lucklist'][$luckkey];
			$res['isjie']=1;
			$res['luckkey']=$luckkey;
			$res['setdesc']=$nickname.'恭喜您！成功借得好运气，享受更好折扣！';
			pdo_update('core_members',array('luckkey'=>$luckkey),array('id'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid']));
			pdo_insert('jy_weishop_member_lucklog',array('luckkey'=>$luckkey,'isjie'=>1,'mid'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid'],'createtime'=>TIMESTAMP));		
		}
		$res['setbg']=$sale_luck['bg'];		
		return $res;
	}
	public function getnew($check=false){
		$sale_new=$this->plugin_setting('sale_new');
		if($sale_new['isopen']!=1){
			return false;
		}
		$res['list']=$sale_new['goods'];
		if(empty($res['list']) || count($res['list'])==0){
			return false;
		}
		$sale_new['days']=$sale_new['days']?:0;
		if($_SESSION['uid']){
			$createtime=pdo_getcolumn('core_members',array('id'=>$_SESSION['uid']),'createtime');
			if($sale_new['days'] && !$check && $createtime<TIMESTAMP-$sale_new['days']*24*3600){
				return false;
			}
		}elseif(!$check){
			return false;
		}
		foreach($res['list'] as $k=>&$v){
			$v['cant_buy']=0;
			$isbuynums = pdo_count('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'goodsid'=>$v['id'],'mid'=>$_SESSION['uid'],'status'=>array(1,2,3,5,6,7,8,10)));
			if($isbuynums){
				if(!$check){
					unset($res['list'][$k]);
				}else{
					$v['cant_buy']=1;
				}
			}
			if(!$_SESSION['uid']){
				$v['cant_buy']=1;
			}
			$options = pdo_getall('jy_weishop_goods_option',array('goodsid'=>$v['id']));
			if(!empty($options)){
				foreach($options as &$op){
					$canbuy=$this->model('goods')->check_buy($v['id'],1,$op['id'],'','',true);
					if($canbuy){
						$v['canbuy']=true;
						$v['optionsid']=$op['id'];
						$v['price']=pdo_getcolumn('jy_weishop_goods_option',array('id'=>$op['id'],'uniacid'=>$_SESSION['uniacid']),'price');
					}
				}
				if(!$v['canbuy']){
					$v['optionsid']=$options[0]['id'];
					$v['price']=pdo_getcolumn('jy_weishop_goods_option',array('id'=>$options[0]['id'],'uniacid'=>$_SESSION['uniacid']),'price');
				}
			}else{
				$v['oldprice']=pdo_getcolumn('jy_weishop_goods',array('id'=>$v['id'],'uniacid'=>$_SESSION['uniacid']),'price');
				$v['canbuy']=$this->model('goods')->check_buy($v['id'],1,'','','',true);
			}
			$v['image']=$v['image']?tomedia($v['image']):'';
		}
		if(empty($res['list']) || count($res['list'])==0){
			return false;
		}
		$res['title']=$sale_offer['title'];
		$res['desc']=$sale_offer['desc'];
		$res['days']=$sale_offer['days'];
		return $res;
	}
	public function getlibao($sale_libaoid=0){
		if(!$sale_libaoid){
			return false;
		}
		$item=$this->pdo_get('sale_libao',array('id'=>$sale_libaoid,'mid'=>$_SESSION['uid']));
		if($item['status']==1){
			exi('已使用的礼包！不能再用了！','error');
		}
		if($item['type']!=1 && $item['type']!=2){
			return false;
		}
		if($item['type']==1){
			$res['list']=$item['del_goods_ids']?json_decode($item['del_goods_ids'],true):array();
		}
		if($item['type']==2){
			$res['list']=$item['zhe_goods_ids']?json_decode($item['zhe_goods_ids'],true):array();
		}
		foreach($res['list'] as $k=>&$v){
			$v['cant_buy']=0;
			$isbuynums = pdo_count('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'goodsid'=>$v['id'],'mid'=>$_SESSION['uid'],'status'=>array(1,2,3,5,6,7,8,10)));
			if($isbuynums){
				if(!$check){
					unset($res['list'][$k]);
				}else{
					$v['cant_buy']=1;
				}
			}
			if(!$_SESSION['uid']){
				$v['cant_buy']=1;
			}
			$options = pdo_getall('jy_weishop_goods_option',array('goodsid'=>$v['id']));
			if(!empty($options)){
				foreach($options as &$op){
					$canbuy=$this->model('goods')->check_buy($v['id'],1,$op['id'],'','',true);
					if($canbuy){
						$v['canbuy']=true;
						$v['optionsid']=$op['id'];
						$v['price']=pdo_getcolumn('jy_weishop_goods_option',array('id'=>$op['id'],'uniacid'=>$_SESSION['uniacid']),'price');
					}
				}
				if(!$v['canbuy']){
					$v['optionsid']=$options[0]['id'];
					$v['price']=pdo_getcolumn('jy_weishop_goods_option',array('id'=>$options[0]['id'],'uniacid'=>$_SESSION['uniacid']),'price');
				}
			}else{
				$v['oldprice']=pdo_getcolumn('jy_weishop_goods',array('id'=>$v['id'],'uniacid'=>$_SESSION['uniacid']),'price');
				$v['canbuy']=$this->model('goods')->check_buy($v['id'],1,'','','',true);
			}
			$v['image']=$v['image']?tomedia($v['image']):'';
		}
		if(empty($res['list']) || count($res['list'])==0){
			return false;
		}
		return $res;
	}
	public function ispay($params){
		$params=array(
			'uniacid'=>$_SESSION['uniacid'],
			'ordersn'=>$params['ordersn'],
		);
		$this->update('activity_sales_log',array('ispay'=>1),$params);
	}
	public function task(){
		$lasttime=time()-600;
		$logs = pdo_getall('jy_weishop_activity_sales_log',array('uniacid'=>$_SESSION['uniacid'],'createtime >'=>$lasttime));
		foreach($logs as $item){
			$status=pdo_getcolumn('jy_weishop_order',array('ordersn'=>$item['ordersn'],'uniacid'=>$_SESSION['uniacid']),'status');
			if($status==0 && $item['createtime']+120<time()){
				pdo_delete('jy_weishop_activity_sales_log',array('id'=>$item['id'],'uniacid'=>$_SESSION['uniacid']));
			}
		}
	}
}